package com.yiqi.liebang.feature.mine.view;

import android.content.Intent;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.Html;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.suozhang.framework.framework.AM;
import com.suozhang.framework.framework.BaseActivity;
import com.suozhang.framework.utils.DateUtil;
import com.yiqi.liebang.R;
import com.yiqi.liebang.common.util.DateTool;
import com.yiqi.liebang.common.widget.dialog.BaseAnimatorSet;
import com.yiqi.liebang.common.widget.dialog.BounceTopEnter;
import com.yiqi.liebang.common.widget.dialog.NormalDialog;
import com.yiqi.liebang.common.widget.dialog.OnBtnClickL;
import com.yiqi.liebang.common.widget.dialog.SlideBottomExit;
import com.yiqi.liebang.entity.bo.WorkBo;
import com.yiqi.liebang.feature.mine.contract.WorkContract;
import com.yiqi.liebang.feature.mine.dependencies.work.DaggerWorkComponent;
import com.yiqi.liebang.feature.mine.dependencies.work.WorkPresenterModule;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;
import io.rong.message.LocationMessage;

import static com.yiqi.liebang.common.util.DateTool.DEFAULT_NYR;
import static com.yiqi.liebang.common.util.DateTool.getMinDate;

public class EditWorkActivity extends BaseActivity implements WorkContract.View, Toolbar.OnMenuItemClickListener, TextWatcher, View.OnTouchListener {

    @BindView(R.id.toolbar)
    Toolbar mToolbar;
    @BindView(R.id.tv_work_starttime)
    TextView mTvWorkStarttime;
    @BindView(R.id.tv_work_endtime)
    TextView mTvWorkEndtime;
    @BindView(R.id.edt_work_name)
    EditText mEdtWorkName;
    @BindView(R.id.edt_work_position)
    EditText mEdtWorkPosition;
    @BindView(R.id.edt_work_desc)
    EditText mEdtWorkDesc;

    @Inject
    WorkContract.Presenter mPresenter;
    @BindView(R.id.tv_edit_intr_count)
    TextView mTvEditIntrCount;
    @BindView(R.id.iv_user_logo)
    ImageView mIvUserLogo;
    @BindView(R.id.btn_work_delete)
    TextView mBtnWorkDelete;


    private BaseAnimatorSet mBasIn;
    private BaseAnimatorSet mBasOut;
    private List<LocalMedia> selectList;

    private String mId = "";
    private boolean isAdd = false;
    private String mCompanyUri;
    private WorkBo mWorkBo;

    private int sign;

    private String mStartTime;
    private String mEndTime;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_edit_work;
    }

    @Override
    protected void initInjector() {
        DaggerWorkComponent.builder().workPresenterModule(new WorkPresenterModule(this)).build().inject(this);
    }

    @Override
    protected void initView() {

        mBasIn = new BounceTopEnter();
        mBasOut = new SlideBottomExit();
        mToolbar.inflateMenu(R.menu.menu_save);
        mToolbar.setOnMenuItemClickListener(this);
    }

    @Override
    protected void initData() {
        isAdd = this.getIntent().getBooleanExtra("isAdd", false);
        sign = this.getIntent().getIntExtra("sign", 999);
        if (isAdd) {
            initToolBar(mToolbar, "新增工作经历", true, true);
            mBtnWorkDelete.setVisibility(View.GONE);
        } else {
            initToolBar(mToolbar, "编辑工作经历", true, true);
            mId = this.getIntent().getStringExtra("id");
            mPresenter.userGetWork(mId);
        }

    }



    @Override
    protected void initEvent() {
        mEdtWorkDesc.addTextChangedListener(this);
        mEdtWorkDesc.setOnTouchListener(this);
    }

    private Date mStartDate = null;

    @OnClick({R.id.btn_work_starttime, R.id.btn_work_endtime, R.id.btn_work_delete, R.id.btn_work_add})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_work_starttime:
                TimePickerView pvTime = new TimePickerBuilder(this, null, new OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {//选中事件回调
                        mStartDate = date;
                        mStartTime = DateTool.date2String(date, DEFAULT_NYR);
                        mTvWorkStarttime.setText(mStartTime);
                    }

                    @Override
                    public void onTimeZhijin(Date date, View v) {

                    }
                })
                        .setType(new boolean[]{true, true, true, false, false, false})// 默认全部显示
                        .setLineSpacingMultiplier(1.8f)
                        .setRangDate(getMinDate(), Calendar.getInstance())
                        .setDate(mStartDate!=null?DateTool.dataToCalendar(mStartDate):Calendar.getInstance())
                        .build();
                pvTime.show();
                break;
            case R.id.btn_work_endtime:
                if (mStartDate == null) {
                    showMsg("请先选择开始时间！");
                    return;
                }
                TimePickerView pvEnd = new TimePickerBuilder(this, null, new OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {//选中事件回调
                        mEndTime = DateTool.date2String(date, DEFAULT_NYR);
                        mTvWorkEndtime.setText(mEndTime);
                    }

                    @Override
                    public void onTimeZhijin(Date date, View v) {
                        if (date != null) {
                            mEndTime = "至今";
                            mTvWorkEndtime.setText(mEndTime);
                        }
                    }
                })
                        .setType(new boolean[]{true, true, true, false, false, false})// 默认全部显示
                        .setLineSpacingMultiplier(1.8f)
                        .setRangDate(DateTool.dataToCalendar(mStartDate), Calendar.getInstance())
                        .setCancelText("至今")
                        .build();
                pvEnd.show();
                break;
            case R.id.btn_work_delete:
                final NormalDialog dialog = new NormalDialog(this);
                dialog.content("是否删除此工作经历?")
                        .showAnim(mBasIn)//
                        .dismissAnim(mBasOut)//
                        .show();

                dialog.setOnBtnClickL(
                        new OnBtnClickL() {
                            @Override
                            public void onBtnClick() {
                                dialog.dismiss();
                            }
                        },
                        new OnBtnClickL() {
                            @Override
                            public void onBtnClick() {
                                mPresenter.userDeleteWork(mId, sign == 0 ? 1 : 0);
                                dialog.dismiss();
                            }
                        });
                break;
            case R.id.btn_work_add:
//                LocationMessage.obtain()
                if (isAdd) {
                    mPresenter.userAddWork(
                            mCompanyUri,
                            mEdtWorkName.getText().toString(),
                            mEdtWorkPosition.getText().toString(),
                            mTvWorkStarttime.getText().toString(),
                            mTvWorkEndtime.getText().toString(),
                            mEdtWorkDesc.getText().toString());
                } else {
                    mPresenter.userEditWork(
                            mId,
                            mCompanyUri,
                            mEdtWorkName.getText().toString(),
                            mEdtWorkPosition.getText().toString(),
                            mTvWorkStarttime.getText().toString(),
                            mTvWorkEndtime.getText().toString(),
                            mEdtWorkDesc.getText().toString());
                }
                break;
        }
    }

    @Override
    public void showAddWorkSuccess() {
        finish();
    }

    @Override
    public void showWorkSuccess(WorkBo workBo) {

        mStartTime = workBo.getBeginTime();
        mEndTime = workBo.getEndTime();
        if (workBo != null) {
            mStartDate = DateTool.strToDate(workBo.getBeginTime());
        }

        mWorkBo = workBo;
        AM.image().bindToCircleObject(mWorkBo.getComLogo(), mIvUserLogo);
        mEdtWorkName.setText(mWorkBo.getCompany());
        mEdtWorkPosition.setText(mWorkBo.getPosition());
        mTvWorkStarttime.setText(mWorkBo.getBeginTime());
        mTvWorkEndtime.setText(mWorkBo.getEndTime());
        mEdtWorkDesc.setText(mWorkBo.getDescribeInfo());
        mTvEditIntrCount.setText(Html.fromHtml("<font color=\"#2AA0F8\">" + (TextUtils.isEmpty(mWorkBo.getDescribeInfo()) ? 0 : mWorkBo.getDescribeInfo().length()) + "</font>/2000"));
    }

    @Override
    public void showError(String error) {
        showMsg(error);
    }

    @Override
    public boolean onMenuItemClick(MenuItem item) {
        if (isAdd) {
            mPresenter.userAddWork(
                    mCompanyUri,
                    mEdtWorkName.getText().toString(),
                    mEdtWorkPosition.getText().toString(),
                    mStartTime,
                    mEndTime,
                    mEdtWorkDesc.getText().toString());
        } else {
            mPresenter.userEditWork(
                    mId,
                    mCompanyUri,
                    mEdtWorkName.getText().toString(),
                    mEdtWorkPosition.getText().toString(),
                    mStartTime,
                    mEndTime,
                    mEdtWorkDesc.getText().toString());
        }
        return false;
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        mTvEditIntrCount.setText(Html.fromHtml("<font color=\"#2AA0F8\">" + s.toString().length() + "</font>/2000"));
    }


    @OnClick(R.id.btn_edit_logo)
    public void onViewClicked() {
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())
                .theme(R.style.picture_default_style1)
                .selectionMode(PictureConfig.SINGLE)// 多选 or 单选
                .previewImage(true)// 是否可预览图片
                .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                .isCamera(true)
                .enableCrop(true)// 是否裁剪
                .circleDimmedLayer(true)// 是否圆形裁剪 true or false
                .withAspectRatio(1, 1)// int 裁剪比例 如16:9 3:2 3:4 1:1 可自定义
                .compress(true)// 是否压缩
                .hideBottomControls(false)// 是否显示uCrop工具栏，默认不显示
                .isGif(false)// 是否显示gif图片
                .freeStyleCropEnabled(true)// 裁剪框是否可拖拽
                .circleDimmedLayer(true)// 是否圆形裁剪
                .selectionMedia(selectList)// 是否传入已选图片
                .scaleEnabled(true)
                .forResult(PictureConfig.SINGLE);//结果回调onActivityResult code
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == -1) {
            switch (requestCode) {
                case PictureConfig.SINGLE:
                    // 图片选择结果回调
                    selectList = PictureSelector.obtainMultipleResult(data);
                    for (int i = 0; i < selectList.size(); i++) {
                        mCompanyUri = selectList.get(i).getCutPath();
                    }
                    AM.image().bindToCircleObject(mCompanyUri, mIvUserLogo);
                    break;
            }
        }
    }

    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        //触摸的是EditText并且当前EditText可以滚动则将事件交给EditText处理；否则将事件交由其父类处理
        if ((view.getId() == R.id.edt_work_desc && canVerticalScroll(mEdtWorkDesc))) {
            view.getParent().requestDisallowInterceptTouchEvent(true);//告诉父view，我的事件自己处理
            if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                view.getParent().requestDisallowInterceptTouchEvent(false);//告诉父view，你可以处理了
            }
        }
        return false;

    }

    /**
     * EditText竖直方向是否可以滚动
     *
     * @param editText 需要判断的EditText
     * @return true：可以滚动   false：不可以滚动
     */
    private boolean canVerticalScroll(EditText editText) {
        //滚动的距离
        int scrollY = editText.getScrollY();
        //控件内容的总高度
        int scrollRange = editText.getLayout().getHeight();
        //控件实际显示的高度
        int scrollExtent = editText.getHeight() - editText.getCompoundPaddingTop() - editText.getCompoundPaddingBottom();
        //控件内容总高度与实际显示高度的差值
        int scrollDifference = scrollRange - scrollExtent;

        if (scrollDifference == 0) {
            return false;
        }

        return (scrollY > 0) || (scrollY < scrollDifference - 1);
    }

}
